package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.CertificateNewsService;
import com.jinzhi.jzweb.service.CertificateProfileService;
import com.jinzhi.jzweb.service.CertificationBatchService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 
 * <pre>
 * 认证批次
 * </pre>
 * <small> 2020-02-24 21:00:12 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/certificationBatch")
public class CertificationBatchController extends BaseController {
	@Autowired
	private CertificationBatchService certificationBatchService;
	@Autowired
	private UserService userService;
	@Autowired
	private CertificateProfileService certificateProfileService;
	@Autowired
	private CertificateNewsService certificateNewsService;

	@GetMapping()
	@RequiresPermissions("jzweb:certificationBatch:certificationBatch")
	String CertificationBatch(){
	    return "jzweb/certificationBatch/certificationBatch";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:certificationBatch:certificationBatch")
	public Result<Page<CertificationBatchDO>> list(CertificationBatchDO certificationBatchDTO){
		Wrapper<CertificationBatchDO> wrapper = new EntityWrapper<CertificationBatchDO>().orderBy("id", false);
		if (certificationBatchDTO.getState() != null){
			wrapper.eq("state",certificationBatchDTO.getState());
		}
		if (certificationBatchDTO.getName() != null){
			wrapper.like("name",certificationBatchDTO.getName());
		}
		if (StringUtils.isNotBlank(certificationBatchDTO.getProfileName())){
			Wrapper<CertificateProfileDO> cerWrapper = new EntityWrapper<CertificateProfileDO>().like("name",certificationBatchDTO.getProfileName());
			List<CertificateProfileDO>  certificateProfileDOS = certificateProfileService.selectList(cerWrapper);
			String str = "";
			for (CertificateProfileDO certificateProfileDO : certificateProfileDOS){
				str = str + certificateProfileDO.getId() + ",";
			}
			wrapper.and();
			if(StringUtils.isNotBlank(str)){
				wrapper.in("profile_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("profile_id",null);
			}
		}

		Page<CertificationBatchDO> page = certificationBatchService.selectPage(getPage(CertificationBatchDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			CertificationBatchDO obj = (CertificationBatchDO) page.getRecords().get(i);
			if (obj.getCreaterId() != null){
				UserDO userDO = userService.selectById(obj.getCreaterId());
				if (userDO != null) {
					obj.setCreaterName(userDO.getUsername());
				}
			}
			if(obj.getNewsId() != null){
				CertificateNewsDO certificateNewsDO = certificateNewsService.selectById(obj.getNewsId());
				if(certificateNewsDO != null){
					CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(certificateNewsDO.getProfileId());
					if(certificateProfileDO != null){
						if(certificateNewsDO.getGrade() == 0){
							obj.setProfileName(certificateProfileDO.getName()+"(高级)");
						}else if(certificateNewsDO.getGrade() == 1){
							obj.setProfileName(certificateProfileDO.getName()+"(中级)");
						}else if(certificateNewsDO.getGrade() == 2){
							obj.setProfileName(certificateProfileDO.getName()+"(初级)");
						}else{
							obj.setProfileName(certificateProfileDO.getName());
						}
					}
				}
			}
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:certificationBatch:add")
	String add(Model model){
		model.addAttribute("certificateProfile",certificateNewsService.selByNewId());
	    return "jzweb/certificationBatch/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:certificationBatch:edit")
	String edit(@PathVariable("id") Long id,Model model){
		model.addAttribute("certificateProfile",certificateNewsService.selByNewId());
		CertificationBatchDO certificationBatch = certificationBatchService.selectById(id);
		model.addAttribute("certificationBatch", certificationBatch);
	    return "jzweb/certificationBatch/edit";
	}
	
	@Log("添加认证批次")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:certificationBatch:add")
	public Result<String> save(CertificationBatchDO certificationBatch){
		if(certificationBatch.getNewsId() != null){
			CertificateNewsDO certificateNewsDO = certificateNewsService.selectById(certificationBatch.getNewsId());
			if(certificateNewsDO != null){
				certificationBatch.setProfileId(certificateNewsDO.getProfileId());
			}
		}
		//根据认证批次名称、证书信息id，证书概况id判断认证批次是否重复，通过不同认证批次名称，可以设置多条
		CertificationBatchDO certificationBatchDO = certificationBatchService
				.findOneByKv("name", certificationBatch.getName(), "news_id", certificationBatch.getNewsId(), "profile_id", certificationBatch.getProfileId());
		if (certificationBatchDO != null) {
			return Result.fail("认证批次已存在！（如报名时间不同，直接修改认证批次名称即可）");
		} else {
			certificationBatch.setCreaterId(this.getUserId());
			certificationBatchService.insert(certificationBatch);
			return Result.ok();
		}
	}
	
	@Log("修改认证批次")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:certificationBatch:edit")
	public Result<String> update(CertificationBatchDO certificationBatch){
		//根据认证批次名称、证书信息id，证书概况id判断认证批次是否重复，通过不同认证批次名称，可以设置多条
		List<CertificationBatchDO> certificationBatchDO = certificationBatchService
				.findByKv("name", certificationBatch.getName(), "news_id", certificationBatch.getNewsId(), "profile_id", certificationBatch.getProfileId());
		if (certificationBatchDO != null && certificationBatchDO.size() > 0) {
			if (certificationBatchDO.size() == 1) {
				if (certificationBatchDO.get(0).getId().equals(certificationBatch.getId())) {
					boolean update = certificationBatchService.updateById(certificationBatch);
					return update ? Result.ok() : Result.fail();
				}
			}
			return Result.fail("认证批次已存在！（如报名时间不同，直接修改认证批次名称即可）");
		} else {
			boolean update = certificationBatchService.updateById(certificationBatch);
			return update ? Result.ok() : Result.fail();
		}
	}
	
	@Log("删除认证批次")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:certificationBatch:remove")
	public Result<String>  remove( Long id){
		certificationBatchService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除认证批次")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:certificationBatch:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		certificationBatchService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}
	
}
